package handler

import (
	"chat/api/request"
	"chat/consts"
	"chat/intermal/dao"
	"chat/intermal/model"
	"chat/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})

}

func Reginster(c *gin.Context) {
	var req request.RegisterReq
	var err error
	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code":    http.StatusOK,
			"message": "验证失败",
			"data":    false,
		})
		return
	}
	var user model.User
	dao.GetOneFile(&model.User{Mobile: req.Mobile}, &user)
	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
	}
	dao.Create(&user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"Code":    http.StatusOK,
			"message": "注册失败",
			"data":    false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"Code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.Id,
	})
	return
}

func Login(c *gin.Context) {
	var req request.LoginReq
	var err error
	if err = c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"Code":    http.StatusOK,
			"message": "验证失败",
			"data":    false,
		})
		return
	}
	var user model.User
	dao.GetOneFile(&model.User{Mobile: req.Mobile}, &user)
	if user.Id == 0 && pkg.Md5(req.Password) != user.Password {
		c.JSON(http.StatusOK, gin.H{
			"Code":    http.StatusOK,
			"message": "账号密码错误",
			"data":    false,
		})
		return
	}
	token := pkg.CreateToken(uint(user.Id), 24*time.Hour, consts.JWT_KEY)
	c.JSON(http.StatusOK, gin.H{
		"Code":    http.StatusOK,
		"message": "登陆成功",
		"data":    token,
	})
	return
}
